﻿using UnityEngine;
using System.Collections;

public class BallUserController : MonoBehaviour
{
    public BallData WoodBall;
    public BallData MetalBall;
    public BallData RubberBall;

    public BallPropotype BallType { get; private set; }

    public BallData SelectBall { get; private set; }
    Ball ball;
    float hor;
    Coroutine changeBall = null;
    [HideInInspector]
    public bool EnableInput = true;

    private void Awake()
    {
        SelectBall = WoodBall;
        ball = GetComponent<Ball>();
    }
    private void Start()
    {
        BallData.Lerp(ball.CurrentBallData, SelectBall, ball.CurrentBallData, 1f);
        ball.CurrentBallData.Layer = SelectBall.Layer;
        ball.SetBall();
    }
    private void Update()
    {
        if (changeBall == null)
        {
            if (SelectBall != WoodBall && Input.GetButtonDown(Constants.Text_ToWoodBall))
            {
                SelectBall = WoodBall;
                BallType = BallPropotype.Wood;
                changeBall = StartCoroutine(ChangeBall());
            }
            else if (SelectBall != MetalBall && Input.GetButtonDown(Constants.Text_ToMetalBall))
            {
                SelectBall = MetalBall;
                BallType = BallPropotype.Metal;
                changeBall = StartCoroutine(ChangeBall());
            }
            else if (SelectBall != RubberBall && Input.GetButtonDown(Constants.Text_ToRubberBall))
            {
                SelectBall = RubberBall;
                BallType = BallPropotype.Rubber;
                changeBall = StartCoroutine(ChangeBall());
            }
        }
        if (EnableInput)
        {
            ball.Jump(Input.GetButtonDown(Constants.Text_Jump));
            hor = Input.GetAxis(Constants.Text_Horizontal);
        }
        else
            hor = 0; 
    }
    private void FixedUpdate()
    {
        ball.Move(hor);
    }
    IEnumerator ChangeBall()
    {
        float timer = 0f;
        ball.CurrentBallData.Layer = SelectBall.Layer;
        while (timer < 0.25f)
        {
            timer += Time.deltaTime;
            BallData.Lerp(ball.CurrentBallData, SelectBall, ball.CurrentBallData, timer);
            ball.SetBall();
            yield return new WaitForSeconds(Time.deltaTime);
        }
        BallData.Lerp(ball.CurrentBallData, SelectBall, ball.CurrentBallData, 1f);
        ball.SetBall();
        changeBall = null;
    }
}
public enum BallPropotype
{
    Wood,//木质
    Metal,//铁磁性
    Rubber//高弹性
}